package com.example.mobileshop.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.example.mobileshop.models.User;
import com.example.mobileshop.utils.Const;
import com.example.mobileshop.utils.HttpHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class UserController{
	private String URL_NEW_USER = Const.URL_HOST_WS + "/api/v1/users";
	private String URL_LOGIN = Const.URL_HOST_WS + "/oauth/token";
	private HttpClient client = new DefaultHttpClient();
	private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create(); 
	
	public String createNewUser(User user){		
		HttpPost postMethod = new HttpPost(URL_NEW_USER);	
		String responseData = "";
		try {
			String json = gson.toJson(user);
			StringEntity entity;
			
			entity = new StringEntity(json);				
			postMethod.setEntity(entity);
			postMethod.setHeader("Accept", "application/json");
			postMethod.setHeader("Content-type", "application/json");
		    HttpResponse response;			
		    response = client.execute(postMethod);			
		    responseData = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();					    
		} catch(Exception e) {
			e.printStackTrace();
		}	
		return responseData;
	}
	
	public HttpResponse authenticateUser(User user){
		HttpResponse response = null;
		try {						
			if(user != null){
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
		        nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
		        nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
		        nameValuePairs.add(new BasicNameValuePair("client_id", Const.OUR_CLIENT_ID));
		        nameValuePairs.add(new BasicNameValuePair("client_secret", Const.OUR_CLIENT_SECRET));								    
			    HttpHandler httpHandler = new HttpHandler();
			    response = httpHandler.postRequestWithParams(URL_LOGIN, nameValuePairs);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}	
		return response;
	}
}